﻿Imports DotNetNuke
Imports DotNetNuke.Entities.Tabs
Imports DotNetNuke.Entities.Portals
Imports DotNetNuke.Services.Localization
Imports DotNetNuke.Services.Exceptions.Exceptions
Imports DotNetNuke.UI
Imports DotNetNuke.Common.Utilities
Imports DotNetNuke.Common.Globals
Imports System.IO

Partial Public Class SitemapSettings
	Inherits Entities.Modules.PortalModuleBase

	Protected Property CurrentMode() As String
		Get
			If ViewState("mode") Is Nothing Then
				Return "view"
			Else
				Return ViewState("mode").ToString()
			End If
		End Get
		Set(ByVal value As String)
			ViewState("mode") = value
		End Set
	End Property

	Private Sub LoadConfiguration()
		' core settings
		chkLevelPriority.Checked = Boolean.Parse(PortalController.GetPortalSetting("SitemapLevelMode", PortalId, "False"))
		txtMinPagePriority.Text = PortalController.GetPortalSetting("SitemapMinPriority", PortalId, "0.1")
		chkIncludeHidden.Checked = Boolean.Parse(PortalController.GetPortalSetting("SitemapIncludeHidden", PortalId, "False"))

		' General settings
		txtExcludePriority.Text = PortalController.GetPortalSetting("SitemapExcludePriority", PortalId, "0")
		chkCache.Checked = Boolean.Parse(PortalController.GetPortalSetting("SitemapCached", PortalId, "False"))
		If chkCache.Checked Then
			txtCacheDays.Text = PortalController.GetPortalSetting("SitemapCacheDays", PortalId, "1")
		End If
		lnkResetCache.Visible = chkCache.Checked

		' load pages
		pnlSave.Visible = False
		BindGrid()

		' load providers
		BindProviders()
	End Sub

	Private Sub SavePrioritySettings()
		PortalController.UpdatePortalSetting(PortalId, "SitemapLevelMode", chkLevelPriority.Checked.ToString())

		If Single.Parse(txtMinPagePriority.Text) < 0 Then
			txtMinPagePriority.Text = "0"
		End If
		PortalController.UpdatePortalSetting(PortalId, "SitemapMinPriority", txtMinPagePriority.Text)

	End Sub

	Private Sub SaveProvidersSettings()
		For Each item As DataGridItem In grProviders.Items
			Dim lblProviderName As Label = CType(item.FindControl("lblProviderName"), Label)
			Dim chkEnabled As CheckBox = CType(item.FindControl("chkEnabled"), CheckBox)
			Dim chkOverride As CheckBox = CType(item.FindControl("chkOverride"), CheckBox)
			Dim txtValue As TextBox = CType(item.FindControl("txtValue"), TextBox)

			PortalController.UpdatePortalSetting(PortalId, lblProviderName.Text + "Enabled", chkEnabled.Checked.ToString())
			PortalController.UpdatePortalSetting(PortalId, lblProviderName.Text + "Override", chkOverride.Checked.ToString())
			Dim val As Single
			If chkOverride.Checked Then
				If (Not Single.TryParse(txtValue.Text, val)) Then
					val = 0.5
				End If
				' stored as an integer (pr * 100) to prevent from translating errors with the decimal point
				PortalController.UpdatePortalSetting(PortalId, lblProviderName.Text + "Value", val * 100)
			End If
		Next

	End Sub

	Private Sub ResetCache()

		For Each file As String In System.IO.Directory.GetFiles(PortalSettings.HomeDirectoryMapPath + "sitemap\", "sitemap*.xml")
			System.IO.File.Delete(file)
		Next
		DotNetNuke.UI.Skins.Skin.AddModuleMessage(Me, Localization.GetString("ResetOK", LocalResourceFile), Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess)

	End Sub

	Private Function IsChildPortal(ByVal ps As PortalSettings, ByVal context As HttpContext) As Boolean
		Dim isChild As Boolean = False
		Dim portalName As String
		Dim aliasController As New PortalAliasController
		Dim arr As ArrayList = aliasController.GetPortalAliasArrayByPortalID(ps.PortalId)
		Dim serverPath As String = DotNetNuke.Common.Globals.GetAbsoluteServerPath(context.Request)

		If arr.Count > 0 Then
			Dim portalAlias As PortalAliasInfo = CType(arr(0), PortalAliasInfo)
			portalName = DotNetNuke.Common.Globals.GetPortalDomainName(ps.PortalAlias.HTTPAlias)
			If Convert.ToBoolean(InStr(1, portalAlias.HTTPAlias, "/")) Then
				portalName = Mid(portalAlias.HTTPAlias, InStrRev(portalAlias.HTTPAlias, "/") + 1)
			End If
			If portalName <> "" AndAlso System.IO.Directory.Exists(serverPath & portalName) Then
				isChild = True
			End If
		End If
		Return isChild
	End Function

#Region "Page Grid"
	Private CurrentPage As Integer = 1
	Private TotalRecords As Integer
	Private PageSize As Integer = 5

	Private Sub BindGrid()
		Dim tabs As List(Of TabInfo)
		tabs = TabController.GetPortalTabs(PortalId, Null.NullInteger, False, chkIncludeHidden.Checked, False, False)
		TotalRecords = tabs.Count

		grPages.DataSource = tabs.GetRange((CurrentPage - 1) * PageSize, Math.Min(PageSize, TotalRecords - (CurrentPage - 1) * PageSize))
		grPages.DataBind()

		ctlPagingControl.TotalRecords = TotalRecords
		ctlPagingControl.PageSize = PageSize
		ctlPagingControl.CurrentPage = CurrentPage
		ctlPagingControl.TabID = TabId

	End Sub

	''' <summary>
	''' When page level priority is used, the priority for each page will be computed from 
	''' the hierarchy level of the page. 
	''' Top level pages will have a value of 1, second level 0.9, third level 0.8, ... 
	''' and sixth level and up will have a value of 0.4
	''' </summary>
	''' <param name="tabPriority"></param>
	''' <param name="level"></param>
	''' <returns></returns>
	''' <remarks></remarks>
	Protected Function GetPriority(ByVal tabPriority As Single, ByVal level As Integer) As Single
		Dim priority As Single = tabPriority

		If chkLevelPriority.Checked Then
			If level >= 9 Then
				priority = 0.1
			Else
				priority = CSng(1 - (level * 0.1))
			End If

			If priority < Single.Parse(txtMinPagePriority.Text) Then
				priority = Single.Parse(txtMinPagePriority.Text)
			End If
		End If
		Return priority
	End Function

#End Region

#Region "Providers Grid"
	Private Sub BindProviders()
		Dim builder As New SitemapBuilder(PortalSettings)
		grProviders.DataSource = CType(builder.Providers, IEnumerable)
		grProviders.DataBind()
	End Sub

	Protected Function GetProviderStatus(ByVal name As String) As Boolean

		Return Boolean.Parse(PortalController.GetPortalSetting(name + "Enabled", PortalId, "True"))

	End Function

	Protected Function GetProviderPriorityOverrided(ByVal name As String) As Boolean

		Return Boolean.Parse(PortalController.GetPortalSetting(name + "Override", PortalId, "False"))

	End Function

	Protected Function GetProviderPriorityValue(ByVal name As String) As String

		Dim value As String = ""
		If (Boolean.Parse(PortalController.GetPortalSetting(name + "Override", PortalId, "False"))) Then
			' stored as an integer (pr * 100) to prevent from translating errors with the decimal point
			Dim pr As Single = PortalController.GetPortalSetting(name + "Value", PortalId, 50) / 100
			value = pr.ToString("F01")
		End If
		Return value

	End Function
#End Region

	''' -----------------------------------------------------------------------------
	''' <summary>
	''' Page_Load runs when the control is loaded
	''' </summary>
	''' <remarks>
	''' </remarks>
	''' <history>
	''' </history>
	''' -----------------------------------------------------------------------------
	Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
		Try
			If Not Request.QueryString("CurrentPage") Is Nothing Then
				CurrentPage = CType(Request.QueryString("CurrentPage"), Integer)
			End If

			If Page.IsPostBack = False Then
				Localization.LocalizeDataGrid(grPages, LocalResourceFile)
				Localization.LocalizeDataGrid(grProviders, LocalResourceFile)

				If IsChildPortal(PortalSettings, Context) Then
					txtSiteMap.Text = AddHTTP(GetDomainName(Request)) & "/SiteMap.aspx?portalid=" & PortalId.ToString
				Else
					txtSiteMap.Text = AddHTTP(PortalSettings.PortalAlias.HTTPAlias) & "/SiteMap.aspx"
				End If
				lnkTestSitemap.NavigateUrl = txtSiteMap.Text

				LoadConfiguration()
			End If

		Catch exc As Exception
			ProcessModuleLoadException(Me, exc)
		End Try
	End Sub

	Protected Sub lnkCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkCancel.Click
		pnlEdit.Visible = True
		pnlSave.Visible = False
		CurrentMode = "view"
		BindGrid()
	End Sub

	Protected Sub lnkEdit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkEdit.Click
		pnlEdit.Visible = False
		pnlSave.Visible = True
		CurrentMode = "edit"
		BindGrid()
	End Sub

	Protected Sub lnkSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkSave.Click

		Dim lbltabid As Label
		Dim txtpriority As TextBox
		Dim txtDescription As TextBox
		Dim txtKeywords As TextBox
		Dim objTab As DotNetNuke.Entities.Tabs.TabInfo
		Dim tabCtl As New TabController

		For Each item In grPages.Items
			lbltabid = CType(item.FindControl("lblTabId"), Label)
			txtDescription = CType(item.FindControl("txtDescription"), TextBox)
			txtKeywords = CType(item.FindControl("txtKeywords"), TextBox)
			txtpriority = CType(item.FindControl("txtPriority"), TextBox)

			objTab = tabCtl.GetTab(Integer.Parse(lbltabid.Text), PortalId, False)
			If Not chkLevelPriority.Checked Then
				objTab.SiteMapPriority = Single.Parse(txtpriority.Text)
			End If
			objTab.Description = txtDescription.Text
			objTab.KeyWords = txtKeywords.Text
			tabCtl.UpdateTab(objTab)
		Next
		pnlEdit.Visible = True
		pnlSave.Visible = False
		CurrentMode = "view"
		BindGrid()

		DotNetNuke.UI.Skins.Skin.AddModuleMessage(Me, Localization.GetString("MessageUpdated", LocalResourceFile), Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess)
	End Sub

	Private Sub lnkSaveAll_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkSaveAll.Click

		SavePrioritySettings()

		PortalController.UpdatePortalSetting(PortalId, "SitemapIncludeHidden", chkIncludeHidden.Checked.ToString())
		PortalController.UpdatePortalSetting(PortalId, "SitemapExcludePriority", txtExcludePriority.Text)
		PortalController.UpdatePortalSetting(PortalId, "SitemapCached", chkCache.Checked.ToString())
		Dim cacheDays As Integer
		If Not Integer.TryParse(txtCacheDays.Text, cacheDays) Then
			cacheDays = 1
		End If
		PortalController.UpdatePortalSetting(PortalId, "SitemapCacheDays", cacheDays.ToString())

		SaveProvidersSettings()

		DotNetNuke.UI.Skins.Skin.AddModuleMessage(Me, Localization.GetString("MessageUpdated", LocalResourceFile), Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess)

		pnlEdit.Visible = True
		pnlSave.Visible = False
		CurrentMode = "view"
		If chkCache.Checked Then
			ResetCache()
		End If

		LoadConfiguration()

	End Sub

	Private Sub lnkRefresh_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkRefresh.Click
		CurrentMode = "view"
		pnlSave.Visible = False

		grPages.CurrentPageIndex = 0
		BindGrid()
		BindGrid()
	End Sub

	Private Sub lnkResetCache_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkResetCache.Click

		ResetCache()

	End Sub

#Region "Site Marketing"
	Protected Sub cmdSearchEngine_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSearchEngine.Click
		Try
			If Not cboSearchEngine.SelectedItem Is Nothing Then
				Dim strURL As String = ""
				Select Case cboSearchEngine.SelectedItem.Text
					Case "Google"
						strURL += "http://www.google.com/addurl?q=" & HTTPPOSTEncode(AddHTTP(GetDomainName(Request)))
						strURL += "&dq="
						If PortalSettings.PortalName <> "" Then
							strURL += HTTPPOSTEncode(PortalSettings.PortalName)
						End If
						If PortalSettings.Description <> "" Then
							strURL += HTTPPOSTEncode(PortalSettings.Description)
						End If
						If PortalSettings.KeyWords <> "" Then
							strURL += HTTPPOSTEncode(PortalSettings.KeyWords)
						End If
						strURL += "&submit=Add+URL"
					Case "Yahoo"
						strURL = "http://siteexplorer.search.yahoo.com/submit"
					Case "Microsoft"
						strURL = "http://search.msn.com.sg/docs/submit.aspx"
				End Select

				UrlUtils.OpenNewWindow(Me.Page, Me.GetType(), strURL)
			End If
		Catch exc As Exception
			ProcessModuleLoadException(Me, exc)
		End Try
	End Sub

	Protected Sub cmdSiteMap_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSiteMap.Click
		UrlUtils.OpenNewWindow(Me.Page, Me.GetType(), "http://www.google.com/webmasters/sitemaps/")
	End Sub

	Protected Sub cmdVerification_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdVerification.Click
		If txtVerification.Text <> "" AndAlso txtVerification.Text.EndsWith(".html") Then
			If Not File.Exists(ApplicationMapPath & "\" & txtVerification.Text) Then
				' write SiteMap verification file
				Dim objStream As StreamWriter
				objStream = File.CreateText(ApplicationMapPath & "\" & txtVerification.Text)
				objStream.WriteLine("Google SiteMap Verification File")
				objStream.WriteLine(" - " & txtSiteMap.Text)
				objStream.WriteLine(" - " & UserInfo.DisplayName)
				objStream.Close()
			End If
		End If
	End Sub


#End Region

End Class
